package producerConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @program: javase
 * @description: 指定唤醒的线程，a->b->c,交替打印123
 * @author: lld
 * @create: 2021-04-17 21:09
 **/
public class ConditionDemo {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data3.a();

            }
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data3.b();
            }
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                data3.c();
            }
        }, "C").start();
    }
}

class Data3 {
    private Lock lock = new ReentrantLock();
    private Condition condition1 = lock.newCondition();
    private Condition condition2 = lock.newCondition();
    private Condition condition3 = lock.newCondition();
    //num是标志位
    private int num = 1;

    public void a() {
        lock.lock();
        try {
//        判断等待->业务->唤醒
            while (num != 1) {
                condition1.await();
            }
            num = 2;
            System.out.println(Thread.currentThread().getName() + ">> 1");
            //唤醒b
            condition2.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void b() {
        lock.lock();
        try {
//        判断等待->业务->唤醒
            while (num != 2) {
                condition2.await();
            }
            num = 3;
            System.out.println(Thread.currentThread().getName() + ">> 2");
            //唤醒c
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void c() {
        lock.lock();
        try {
//        判断等待->业务->唤醒
            while (num != 3) {
                condition3.await();
            }
            num = 1;
            System.out.println(Thread.currentThread().getName() + ">> 3");
            //唤醒b
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

